﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

namespace Microsoft.Expression.Prototyping.Mockups
{
	using System;
	using System.Windows;
	using System.Windows.Controls;

	public class MiniWrapPanel : Panel
	{
		protected override Size MeasureOverride(Size availableSize)
		{
			double maxRowHeight = 0;
			double maxColumWidth = 0;

			Point currentPosition = new Point();

			foreach (FrameworkElement child in this.Children)
			{
				child.Measure(availableSize);
				Size desiredSize = child.DesiredSize;

				if (desiredSize.Width + currentPosition.X > availableSize.Width && currentPosition.X != 0)
				{
					currentPosition.Y += maxRowHeight;
					maxColumWidth = Math.Max(maxColumWidth, currentPosition.X);
					currentPosition.X = desiredSize.Width;
					maxRowHeight = desiredSize.Height;
				}
				else
				{
					currentPosition.X += desiredSize.Width;
					maxRowHeight = Math.Max(maxRowHeight, desiredSize.Height);
				}
			}

			maxColumWidth = Math.Max(maxColumWidth, currentPosition.X);

			return new Size(maxColumWidth, currentPosition.Y + maxRowHeight);
		}

		protected override Size ArrangeOverride(Size finalSize)
		{

			double maxRowHeight = 0;
			Point currentPosition = new Point();

			foreach (FrameworkElement child in this.Children)
			{
				Size desiredSize = child.DesiredSize;
				if (desiredSize.Width + currentPosition.X > finalSize.Width && currentPosition.X != 0)
				{
					currentPosition.X = 0;
					currentPosition.Y += maxRowHeight;
					child.Arrange(new Rect(currentPosition.X, currentPosition.Y, desiredSize.Width, desiredSize.Height));
					currentPosition.X += desiredSize.Width;
					maxRowHeight = desiredSize.Height;
				}
				else
				{
					child.Arrange(new Rect(currentPosition.X, currentPosition.Y, desiredSize.Width, desiredSize.Height));
					currentPosition.X += desiredSize.Width;
					maxRowHeight = Math.Max(maxRowHeight, desiredSize.Height);
				}
			}

			return finalSize;
		}
	}
}
